package com.java.mall_imooc.controller;

import com.github.pagehelper.PageInfo;
import com.java.mall_imooc.common.utils.PageUtils;
import com.java.mall_imooc.common.utils.R;
import com.java.mall_imooc.entity.Order;
import com.java.mall_imooc.interceoter.LoginInterceptor;
import com.java.mall_imooc.service.OrderService;
import com.java.mall_imooc.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;


/**
 * 订单表
 *
 * @author jl
 * @since 2020-03-14 23:41:10
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    /**
     * 查询订单
     */
    @GetMapping
    public R<PageInfo> list(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        return orderService.list(LoginInterceptor.getUserInfo().getUserId(), pageNum, pageSize);
    }

    /**
     * 创建订单
     */
    @PostMapping("{shippingId}")
    public R<OrderVo> create(@PathVariable("shippingId") Integer shippingId) {
        return orderService.create(LoginInterceptor.getUserInfo().getUserId(), shippingId);
    }

    /**
     * 查询订单详情
     */
    @GetMapping("{orderNo}")
    public R<OrderVo> detail(@PathVariable("orderNo")Long orderNo) {
        return orderService.detail(LoginInterceptor.getUserInfo().getUserId(),orderNo);
    }

    /**
     * 取消订单
     */
    @PutMapping("{orderNo}")
    public R cancel(@PathVariable("orderNo")Long orderNo) {
        return orderService.cancel(LoginInterceptor.getUserInfo().getUserId(),orderNo);
    }

    /**
     * 分页查询order
     * 当前页码page、每页显示记录数limit
     */
    @GetMapping("/list")
    public R list(Order order, @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        if (pageNum < 1) pageNum = 1;
        if (pageSize > 100) pageSize = 100;
        PageUtils page = orderService.queryPage(order, pageNum, pageSize);

        return R.ok(page);
    }


    /**
     * 根据主键查询order
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id) {
        Order order = orderService.getById(id);

        return R.ok(order);
    }

    /**
     * 新增order
     */
    @PostMapping("/save")
    public R save(@RequestBody Order order) {
        orderService.save(order);

        return R.ok();
    }

    /**
     * 修改order
     */
    @PutMapping("/update")
    public R update(@RequestBody Order order) {
        orderService.updateById(order);

        return R.ok();
    }

    /**
     * 删除order
     */
    @DeleteMapping("/delete")
    public R delete(@RequestBody Integer[] ids) {
        orderService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
